<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 警告框 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" show-icon :closable="false">
      </el-alert>
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="4"><span class="text-label">选择商品的分类：</span></el-col>
        <el-col :span="8">
          <el-cascader v-model="pid" :options="pcategories" :props="prop" clearable @change="selectChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- 内容主题区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">

        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" @click="openDialog" :disabled="pid.length !==3 ? true : false">添加参数</el-button>
          <el-table style="width: 100%; margin-top: 20px" border stripe :data="paramList">
            <!-- 展开列 -->
            <el-table-column type="expand" class="children-box">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#">

            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
            <el-table-column fixed="right" label="操作" width="300">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="small" @click="open_Edit(scope.row)">编辑
                </el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="small" @click="confirm_del(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" @click="openDialog" :disabled="pid.length !==3 ? true : false">添加属性</el-button>
          <el-table style="width: 100%; margin-top: 20px" border stripe :data="paramList">
            <!-- 展开列 -->
            <el-table-column type="expand" class="children-box">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称"> </el-table-column>
            <el-table-column fixed="right" label="操作" width="300">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="small" @click="open_Edit(scope.row)">编辑
                </el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="small" @click="confirm_del(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数弹框 -->
    <el-dialog :title="this.activeName=='many'? '动态参数':'静态属性'" :visible.sync="Dialog" width="50%">
      <!-- 内容主体区域 -->
      <el-form label-width="80px" :model="attrForm" :rules="attrFormRule" ref="attrFormRef"
        @close="resetAddForm('attrFormRef')">
        <el-form-item :label="this.activeName=='many'? '动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="attrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="Dialog = false">取 消</el-button>
        <el-button type="primary" @click="submitAddAttr('attrFormRef')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数弹框 -->
    <el-dialog :title="this.activeName=='many'? '动态参数':'静态属性'" :visible.sync="editDialog" width="50%">
      <!-- 内容主体区域 -->
      <el-form label-width="80px" :model="editForm" :rules="attrFormRule" ref="editFormRef"
        @close="resetAddForm('editFormRef')">
        <el-form-item :label="this.activeName=='many'? '动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitEditAttr('editFormRef')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 获取父级分类的数据列表
      pcategories: [],
      // 参数列表
      paramList: [],
      // 选中的分裂的id
      pid: [],
      // 指定级联选择器的配置对象
      prop: {
        children: 'children',
        label: 'cat_name',
        value: 'cat_id',
        expandTrigger: 'hover'
      },
      // 添加参数弹框
      Dialog: false,
      editDialog: false,
      attrForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: '',
        attr_id: '',
        cat_id: '',
        attr_sel: ''
      },
      attrFormRule: {
        attr_name: [{
          required: true,
          message: '请输入参数名称',
          trigger: 'blur'
        }]
      },
      // 默认tab选中页面
      activeName: 'only',
      dynamicTags: [],
      // 控制输入框的显示与隐藏
      inputVisible: false,
      // 输入框的文本消息
      inputValue: ''
    }
  },
  created () {
    this.getPcate()
  },
  computed: {
    cateId () {
      if (this.pid.length === 3) {
        return this.pid[2]
      }
      return null
    }
  },
  methods: {
    // 获取父级分类数据
    async getPcate () {
      const {
        data: res
      } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败')
      }
      this.pcategories = res.data
    },
    // 获取参数列表数据
    async getParamList () {
      const {
        data: res
      } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('请求失败！')
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 控制文本框的显示与隐藏，动态添加
        item.inputVisible = false
        item.inputValue = ''
      })
      this.paramList = res.data
    },
    // 监听级联选择器
    async selectChange () {
      if (this.pid.length !== 3 && this.pid.length !== 0) {
        // 清空选中状态
        this.pid = []
        return this.$message.error('只允许为第三级分类设置相关参数！')
      }
      if (this.pid.length === 0) {
        this.paramList = []
        return
      }
      this.getParamList()
    },
    // 监听标签页选中情况
    handleClick () {
      this.getParamList()
    },
    openDialog () {
      this.Dialog = true
    },
    // 提交修改参数表单
    async submitEditAttr (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const {
            data: res
          } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 200) {
            return this.$message.error('添加失败')
          }
          this.getParamList()
          this.editDialog = false
          this.resetAddForm(formName)
          this.$message.success('添加成功')
        } else {
          this.$message.error('添加失败')
          this.editDialog = false
          this.resetAddForm(formName)
          return false
        }
      })
    },
    // 提交添加参数表单
    async submitAddAttr (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const {
            data: res
          } = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.attrForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 201) {
            return this.$message.error('添加失败')
          }
          this.getParamList()
          this.Dialog = false
          this.resetAddForm(formName)
          console.log(res.data)
          this.$message.success('添加成功')
        } else {
          this.$message.error('添加分类失败')
          this.addCate = false
          this.resetAddForm(formName)
          return false
        }
      })
    },
    // 重置表单
    resetAddForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 修改参数对话框
    async open_Edit (edit) {
      this.editForm = edit
      this.editDialog = true
    },
    // 删除参数
    async confirm_del (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const {
        data: res
      } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除信息失败')
      }
      this.getParamList()
      return this.$message.success('删除成功！')
    },

    // 提交修改的参数项
    async saveAttr_vals (row) {
      // 发起请求，提交新增数据
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
    },
    handleClose (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttr_vals(row)
    },
    // 点击按钮显示文本框
    showInput (row) {
      row.inputVisible = true
      // $nextTick方法的作用，就是当页面上元素被重新渲染之后，猜会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 文本框失去焦点或按下enter键
    async handleInputConfirm (row) {
      // 获取文本框内容
      const inputValue = row.inputValue
      if (inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      // 将输入的值添加到子标签数组中
      row.attr_vals.push(inputValue.trim())

      this.saveAttr_vals(row)
      // 提交以后清空
      row.inputVisible = false
      row.inputValue = ''
      return this.$message.success('新增参数项成功！')
    }
  }
}

</script>
<style lang="less" scoped>
  .text-label {
    height: 40px;
    line-height: 40px;
  }

  .el-cascader {
    width: 100%;
  }

  .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

</style>
